package com.cxh.rmsq.ui.activity.self

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.blankj.utilcode.util.ToastUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.databinding.ActivityBindPhoneBinding
import com.cxh.rmsq.model.Resource
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.activity.LoginActivity
import com.cxh.rmsq.ui.activity.TitleBaseActivity
import com.cxh.rmsq.utils.RegexUtils
import com.cxh.rmsq.viewmodel.LoginViewModel
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import io.rong.callkit.util.SPUtils
import io.rong.imkit.feature.resend.ResendManager

/**
 * 绑定手机号
 */
class BindPhoneActivity : TitleBaseActivity(), View.OnClickListener {

    private lateinit var binding: ActivityBindPhoneBinding
    private var loginViewModel: LoginViewModel? = null
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }
    private var userInfoViewModel: UserInfoViewModel? = null
    private var isRequestVerifyCode = false // 是否请求成功验证码


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBindPhoneBinding.inflate(layoutInflater)
        setContentView(binding.root)
        titleBar.tvTitle.text = "修改绑定手机号"
        loginViewModel =
            ViewModelProviders.of(this).get<LoginViewModel>(LoginViewModel::class.java)
        userInfoViewModel = ViewModelProviders.of(this).get(UserInfoViewModel::class.java)

        binding.tvSendCode.setOnClickListener(this)
        binding.tvConfirm.setOnClickListener(this)
        binding.etPhone.addTextChangedListener(
            object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence, start: Int, count: Int, after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                    if (s.length == 11) {
                        binding.etPhone.clearFocus()
                        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                        imm.hideSoftInputFromWindow(binding.etPhone.getWindowToken(), 0)
                    }
                    if (s.length > 0 && !isRequestVerifyCode) {
                        binding.tvSendCode.setEnabled(true)
                    } else {
                        binding.tvSendCode.setEnabled(false)
                    }
                    if (!TextUtils.isEmpty(
                            binding.etPhone.getText().toString().trim())
                    ) {
                        binding.ivClean.setVisibility(View.VISIBLE)
                    } else {
                        binding.ivClean.setVisibility(View.GONE)
                    }
                }

                override fun afterTextChanged(s: Editable) {}
            })

        initData()
    }

    fun initData() {
        loginViewModel!!.getSendCodeState()
            .observe(
                this,
                object : Observer<Resource<String?>> {
                    override fun onChanged(resource: Resource<String?>) {
                        // 提示
                        if (resource.status == Status.SUCCESS) {
                            showToast(R.string.seal_login_toast_send_code_success)
                        } else if (resource.status == Status.LOADING) {
                        } else {
                            showToast(resource.message)
                            binding.tvSendCode.setEnabled(true)
                        }
                    }
                })

        // 等待接受验证码倒计时， 并刷新及时按钮的刷新
        loginViewModel!!
            .codeCountDown
            .observe(
                this,
                object : Observer<Int> {
                   override fun onChanged(integer: Int) {
                        if (integer > 0) {
                            binding.tvSendCode.setText(integer.toString() + "s")
                            isRequestVerifyCode = true
                        } else {
                            // 当计时结束时， 恢复按钮的状态
                            binding.tvSendCode.setEnabled(true)
                            binding.tvSendCode.setText(R.string.seal_login_send_code)
                            isRequestVerifyCode = false
                        }
                    }
                })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_send_code -> {
                if (TextUtils.isEmpty(binding.etPhone.getText().toString().trim())) {
                    showToast(R.string.seal_login_toast_phone_number_is_null)
                    return
                }
                if (!RegexUtils.checkMobile(binding.etPhone.getText().toString().trim())) {
                    showToast("请输入正确的手机号")
                    return
                }
                binding.tvSendCode.setEnabled(false)
                loginViewModel!!.sendCode("86", binding.etPhone.getText().toString().trim())
            }

            R.id.tv_confirm -> {
                if (isFastClick) {
                    return
                }
                if (TextUtils.isEmpty(binding.etPhone.getText().toString().trim())) {
                    showToast(R.string.seal_login_toast_phone_number_is_null)
                    return
                }
                if (TextUtils.isEmpty(binding.etCode.getText().toString().trim())) {
                    showToast(R.string.seal_login_toast_code_is_null)
                    return
                }
                val paramsMap = HashMap<String, Any>()
                paramsMap.put("code", binding.etCode.getText().toString().trim())
                paramsMap.put("mobile", binding.etPhone.getText().toString().trim())
                viewModel.updateMobile(paramsMap) {
                    if (it.code == 200) {
                        ToastUtils.showShort("修改成功")
                        finishLogout(false)
                    } else {
                        com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
                    }
                }
            }
        }
    }

    private fun finishLogout(isAccountDeleted: Boolean) {
        ResendManager.getInstance().removeAllResendMessage()
        logout(isAccountDeleted)
        // 通知退出
        sendLogoutNotify()
        SPUtils.clear(applicationContext)
        com.blankj.utilcode.util.SPUtils.getInstance().clear()
        startActivity(Intent(this, LoginActivity::class.java))
        finish()
    }

    private fun logout(isAccountDeleted: Boolean) {
        if (userInfoViewModel != null) {
            if (isAccountDeleted) {
                userInfoViewModel!!.accountDelete()
            } else {
                userInfoViewModel!!.logout()
            }
        }
    }
}